import { defineStore} from 'pinia'
import txMap from "qqmap-wx-jssdk"
import { showToast, wxGetLocation } from '../lib/ts/util'
import { cityDetail, getUserinfoapi, osInfo } from '../api/index'

const qqmapsdk = new txMap({  //腾讯地图
	key:'QPGBZ-YXLEB-6BYU4-JXFUM-EEF76-PBFIB'    
})


export const useStore = defineStore('main',{
		state:()=>{
			return{
				userinfo:null,
				config:null,
				district:"东城区",
				city:'北京市',
				area_id:'3'
			}
		},
		actions:{
			getUserinfo():Promise<any>{
				let that = this
				return new Promise( async (resolve)=>{
					if(!uni.getStorageSync('token')) return
					let res = await getUserinfoapi()
					resolve(res)
					that.userinfo = res
				})
			},
			async getConfig(){
				this.config = await osInfo()
			},
			//支付
			pay(payData:any,payType:'wechat' | 'alipay'):Promise<boolean>{
				return new Promise((resolve,reject)=>{
					if(payData){
						// #ifdef APP
							uni.requestPayment({
								provider:payType=='wechat'?"wxpay":"alipay",
								orderInfo:payType=='wechat'?JSON.parse(payData):payData,
								success() {resolve(true)},
								fail() {reject(true)},
								cancle(){
									showToast('已取消')
									reject(true)
								}
							})
						// #endif
						
						// #ifdef MP-WEIXIN
							uni.requestPayment({
								provider: "wxpay",
								...payData,
								success() {resolve(true)},
								fail() {reject(true)},
								cancle(){
									showToast('已取消')
									reject(true)
								}
							})
						// #endif
						
					}else{
						resolve(true)
					}
				})
			},
			//获取当前位置
			getLocation(){
				let that = this
				wxGetLocation().then(res=>{
					that.getRegeo(res.latitude,res.longitude).then(async res=>{
						that.city = res.city
						that.district = res.area
						let res2 = await cityDetail(res.area)
						that.area_id = res2.id
						uni.$emit('locationUpdate')
					})
				})
			},
			//逆解析
			getRegeo(lat:number | string,lng:number):Promise<{
					province:string,
					city:string,
					area:string,
					address:string,
					street:string,
					longitude:number,
					latitude:number,
				}>{ 
				let location = lat
				if(lng) location =lat+','+lng
				return new Promise((resolve,reject)=>{
					qqmapsdk.reverseGeocoder({
						location,
						success(res:any){
							let province = res.result.address_component.province
							let city = res.result.address_component.city
							let area = res.result.address_component.district
							let address = res.result.address
							let street = res.result.address_component.street
							resolve({
								province,city,area,address,street,
								longitude:res.result.location.lng,
								latitude:res.result.location.lat,
							})
						},
						fail(err:object){
							reject(err)
						}
					})
				})
			},
		}
})